<script lang="ts" setup>
import PasswordPopup from '@/components/passwordPopup.vue'
import { checkCouponPackOrderApi } from '@/services/eat'
import { getBalanceApi, getHasPayPasswordApi, payBalanceApi } from '@/services/wallet'
import { postPayApi } from '@/pagesGoods/services/pay'
import { useMemberStore, usePhoneStore } from '@/stores'
import { Toast } from '@/utils/tools'
import { onHide, onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { onMounted, ref, computed } from 'vue'
import { getIsFirstOrderApi } from '@/services/home'

const phoneStore = usePhoneStore()
const memberStore = useMemberStore()
const data = ref<any>({})
onLoad((options) => {
  countDown()
  console.log('options', options)
  data.value = JSON.parse(options?.item)
  data.value.type = options?.type
  console.log('data.value?.paidPrice', data.value?.paidPrice)
  getIsFirstOrder()
  if (!data.value.type && Number(memberStore.balanceInfo?.totalBalance) >= data.value?.paidPrice) {
    weixinPay.value = 0
  } else {
    weixinPay.value = 1
  }
})
let loading = ref(false)
const passwordPopupRef = ref()

const tmplIds = ref<string[]>([])
function getIsFirstOrder() {
  getIsFirstOrderApi().then((res) => {
    if (res?.data === 1) {
      tmplIds.value = [
        'gN9DKGzX7t6TdIdfN6OCqeBnW1_rq-M2SkPtOiuBP_M',
        'cvXN4cVzVAtR_H6kZz7CN-7CM_dp1cf7OtOW1S9ywcc',
        'WiLg6P_YrOaHXH8wj7BrYmqIkydnFkDfCm_7ymDnT2E',
      ]
    } else {
      tmplIds.value = [
        'gN9DKGzX7t6TdIdfN6OCqeBnW1_rq-M2SkPtOiuBP_M',
        'cvXN4cVzVAtR_H6kZz7CN-7CM_dp1cf7OtOW1S9ywcc',
      ]
    }
  })
}

onShow(() => {
  loading.value = false
  getBalance()
  getHasPayPassword()
})

// 获取用户钱包余额
const getBalance = async () => {
  const res = await getBalanceApi()
  if (res.code === 200) {
    memberStore.setBalanceInfo(res.data)
  }
}

// 获取用户是否存在支付密码
const getHasPayPassword = async () => {
  const res = await getHasPayPasswordApi()
  if (res.code === 200) {
    memberStore.setHasPayPassword(res.data)
  }
}

// 输入支付密码
async function handleInput(inputList: number[]) {
  payBalance(inputList.join(''))
}

async function payBalance(password?: string) {
  const res = await payBalanceApi({ orderId: data.value.orderId, password })
  if (res?.code === 200) {
    Toast('支付成功')
    uni.redirectTo({
      url: `/pagesGoods/goodsDetails/goodsDetails?orderId=${data.value.orderId}&flag=${true}`,
    })
    passwordPopupRef.value?.close()
  } else {
    loading.value = false
  }
}
/**
 * * 调起支付
 */
const callUpPayment = async () => {
  loading.value = true
  try {
    if (weixinPay.value) {
      console.log('memberStore.userInfo!.openId', memberStore.userInfo!.openId)
      const ret = await checkCouponPackOrderApi({ orderId: data.value.orderId })
      if (!ret?.data) {
        loading.value = false
        return
      }
      const res = await postPayApi({
        openId: memberStore.userInfo!.openId,
        orderId: data.value.orderId,
      })
      loading.value = false
      wx.requestPayment({
        timeStamp: res.data.timeStamp + '',
        nonceStr: res.data.nonceStr,
        package: res.data.packageValue,
        signType: res.data.signType,
        paySign: res.data.paySign,
        success: () => {
          if (data.value.type === 'couponPack') {
            uni.redirectTo({
              url: `/pagesGoods/goodsDetails/goodsDetails?orderId=${
                data.value.orderId
              }&flag=${true}&type=couponPack`,
            })
            return
          }
          uni.redirectTo({
            url: `/pagesGoods/goodsDetails/goodsDetails?orderId=${data.value.orderId}&flag=${true}`,
          })
          uni.getSetting({
            withSubscriptions: true,
            success(alwaysRes) {
              uni.requestSubscribeMessage({
                tmplIds: tmplIds.value, // 这里填写你的模板ID数组
                success(res: any) {
                  if (res['gN9DKGzX7t6TdIdfN6OCqeBnW1_rq-M2SkPtOiuBP_M'] === 'accept') {
                    // 用户同意订阅该模板
                    console.log('用户同意订阅TEMPLATE_ID_1')
                  }
                  if (res['gN9DKGzX7t6TdIdfN6OCqeBnW1_rq-M2SkPtOiuBP_M'] === 'reject') {
                    // 用户拒绝订阅该模板
                    console.log('用户拒绝订阅TEMPLATE_ID_2')
                  }
                  if (res['cvXN4cVzVAtR_H6kZz7CN-7CM_dp1cf7OtOW1S9ywcc'] === 'accept') {
                    // 用户同意订阅该模板
                    console.log('用户同意订阅TEMPLATE_ID_1')
                  }
                  if (res['cvXN4cVzVAtR_H6kZz7CN-7CM_dp1cf7OtOW1S9ywcc'] === 'reject') {
                    // 用户拒绝订阅该模板
                    console.log('用户拒绝订阅TEMPLATE_ID_2')
                  }
                  if (res['WiLg6P_YrOaHXH8wj7BrYmqIkydnFkDfCm_7ymDnT2E'] === 'accept') {
                    // 用户同意订阅该模板
                    console.log('用户同意订阅优惠券发放通知')
                  }
                  if (res['WiLg6P_YrOaHXH8wj7BrYmqIkydnFkDfCm_7ymDnT2E'] === 'reject') {
                    // 用户拒绝订阅该模板
                    console.log('用户拒绝订阅优惠券发放通知')
                  }
                },
                fail(err) {
                  console.error('订阅消息失败', err)
                },
              })
            },
          })
        },
        fail: (error) => {
          console.log(error)
        },
        complete: (complete) => {},
      })
    } else {
      if (memberStore.hasPayPasswordFree && memberStore.hasPayPassword) {
        payBalance()
      } else if (memberStore.hasPayPassword) {
        passwordPopupRef.value?.open()
      } else {
        const isSetting = memberStore.hasPayPassword ? 0 : 1
        uni.navigateTo({
          url: '/pagesWallet/paymentPassword/paymentPassword?isSetting=' + isSetting + '&isBack=1',
        })
      }
    }
  } catch (error) {
    loading.value = false
  }
}

let minutes = ref()
let seconds = ref()
let currentTime = new Date().getTime() // 当前时间
let futureTime = currentTime + 60000 * 3 // 订单倒计时时间
let timeoutId: any = null // 定时器
/**
 * * 倒计时函数
 * @param minutes 倒计时分钟
 * @param seconds 倒计时秒钟
 */
const countDown = () => {
  let startTime = new Date().getTime() // 每次进去循环新的时间
  let difference = futureTime - startTime // 时间差
  let newM = Math.floor((difference / (1000 * 60)) % 60)
  let newS = Math.floor((difference / 1000) % 60)
  if (difference >= 0) {
    minutes.value = Zero(newM)
    seconds.value = Zero(newS)
  }
  timeoutId = setTimeout(() => {
    if (difference <= 0) {
      clearTimeout(timeoutId)
      if (data.value.type === 'couponPack') {
        uni.redirectTo({
          url: `/pagesGoods/goodsDetails/goodsDetails?orderId=${data.value.orderId}&type=couponPack`,
        })
        return
      }
      uni.redirectTo({
        url: `/pagesGoods/goodsDetails/goodsDetails?orderId=${data.value.orderId}`,
      })
    } else {
      countDown()
    }
  }, 1000)
}

onUnload(() => {
  clearTimeout(timeoutId) // 页面卸载删除定时器
  // console.log('进入支付删除定时器')
})
/**
 * @param Zero 补零
 * @param e
 */
const Zero = (e: number) => {
  return e < 10 ? `0${e}` : e + ''
}
/**
 * * 点击返回按钮，提示用户
 */
const onBack = () => {
  uni.showModal({
    title: '温馨提示',
    content: '是否放弃本次支付？',
    cancelText: '放弃支付',
    confirmText: '继续支付',
    confirmColor: '#8ADF4B',
    success: (success: UniApp.ShowModalRes) => {
      if (success.cancel) {
        if (data.value.type === 'couponPack') {
          uni.redirectTo({
            url: `/pagesGoods/goodsDetails/goodsDetails?orderId=${data.value.orderId}&type=couponPack`,
          })
          return
        }
        uni.redirectTo({
          url: `/pagesGoods/goodsDetails/goodsDetails?orderId=${data.value.orderId}`,
        })
      }
    },
  })
}

const weixinPay = ref<number>(0)
</script>

<template>
  <!-- navBar -->
  <view class="navBar" :style="{ paddingTop: phoneStore.phoneInfo?.top + 'px' }">
    <view @tap="onBack" class="iconfont icon_base_left"></view>
    <view class="navBarText">收银台</view>
  </view>
  <view class="price">
    <view class="payPrice" v-if="!data.type"
      ><text>￥</text>{{ Number(data?.paidPrice)?.toFixed(2) }}</view
    >
    <view class="payPrice" v-else><text>￥</text>{{ data.price }}</view>
    <view class="countDown">
      <view class="countDownText">支付剩余时间</view>
      <view class="minute">{{ minutes }}</view>
      <view class="colon">:</view>
      <view class="second">{{ seconds }}</view>
    </view>
  </view>
  <PasswordPopup ref="passwordPopupRef" @finish="handleInput" @close="loading = false" />
  <view
    class="pay"
    :class="Number(memberStore.balanceInfo?.totalBalance) >= data?.paidPrice ? '' : 'opacity'"
    v-if="!data.type"
  >
    <image src="/static/images/yue.png" />
    <view class="payText">余额支付 （剩余￥{{ memberStore.balanceInfo?.totalBalance }}）</view>
    <button
      :disabled="Number(memberStore.balanceInfo?.totalBalance) < data?.paidPrice"
      style="padding: 0; background: transparent"
      :class="
        !weixinPay && Number(memberStore.balanceInfo?.totalBalance) >= data?.paidPrice
          ? 'icon-checked'
          : 'icon-ring'
      "
      @click="weixinPay = 0"
    ></button>
  </view>
  <view class="pay">
    <view class="iconfont icon_weixin"></view>
    <view class="payText">微信支付</view>
    <view :class="weixinPay ? 'icon-checked' : 'icon-ring'" @click="weixinPay = 1"></view>
  </view>
  <view class="tips">
    <view class="iconfont icon_naozhong"><text>温馨提示</text> </view>
    <text class="warn">商品一经售出，不予退换。</text>
    <view class="tipsText">
      <view class="tipsDate"
        >请于 <text>今晚{{ data.saleEndTime }} </text>前取餐，如未及时取餐订单将自动完结，无法使用。
      </view>
      <view class="tipsMobile">
        特殊情况请咨询在线客服或拨打客服热线19128769631，给您带来的不便请谅解！</view
      >
    </view>
  </view>
  <view class="fixed">
    <button :loading="loading" :disabled="loading" @tap="callUpPayment()">确认支付</button>
  </view>
</template>

<style lang="scss">
//
page {
  height: 100vh;
  // background: linear-gradient(180deg, #e3fdea 14.57%, #f5f5f5 95.06%);
  background: linear-gradient(180deg, #e3fdea 0%, #f5f5f5 40.73%);
}
.navBar {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  .iconfont {
    margin-left: 50rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 64rpx;
    height: 64rpx;
    color: #000000e5;
    border-radius: 50%;
    background-color: #fff;
  }
  .navBarText {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    font-size: 32rpx;
    color: #000000e5;
  }
}
.price,
.pay,
.tips {
  width: 702rpx;
  margin: 0 24rpx 20rpx;
  border-radius: 16rpx;
}

.price {
  margin-top: 36rpx;
  height: 296rpx;
  padding-top: 60rpx;
  text-align: center;
  background-color: #fff;
  .payPrice {
    width: 100%;
    color: $uni-color-motif;
    font-size: 72rpx;
    & > text {
      font-size: 32rpx;
    }
  }
  .countDown {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 36rpx;
    height: 40rpx;
    font-size: 22rpx;
    color: #000000e5;
    .minute {
      margin-left: 32rpx;
    }
    .colon {
      margin: 0 20rpx 4rpx;
    }
    .second,
    .minute {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 40rpx;
      height: 40rpx;
      border-radius: 8rpx;
      border: 1px solid #97979733;
    }
  }
}
.pay {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 28rpx;
  height: 116rpx;
  background-color: #fff;
  opacity: 1;
  .icon_weixin,
  .icon-checked {
    color: $uni-color-motif;
  }
  .icon_weixin {
    font-size: 56rpx;
  }
  .payText {
    margin-left: 32rpx;
    flex: 1;
  }
  .icon-checked,
  .icon-ring {
    font-size: 36rpx;
  }
  image {
    width: 56rpx;
    height: 56rpx;
  }
}
.opacity {
  opacity: 0.4;
}
.tips {
  padding: 0 32rpx 30rpx 0;
  border-radius: 16rpx;
  border: 1px dashed #ffa31a;
  .iconfont {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 160rpx;
    height: 40rpx;
    border-radius: 16rpx 0;
    background: #ffa31a;
    color: #fff;
    font-size: 28rpx;
    box-sizing: border-box;
    margin-bottom: 20rpx;
    & > text {
      font-size: 24rpx;
      text-align: center;
      margin: 0 0 4rpx 6rpx;
    }
  }
  .warn {
    margin: 0 0 0 28rpx;
    padding: 0 8rpx;
    border-radius: 8rpx;
    color: #ffa31a;
    background: #ffead4;
    font-size: 24rpx;
  }
  .tipsText {
    margin: 20rpx 0 0 28rpx;
    font-size: 22rpx;
    color: #00000080;
    .tipsDate {
      word-wrap: break-word;
      white-space: normal;
      margin-bottom: 8rpx;
      & > text {
        padding: 0 8rpx;
        margin: 0 4rpx;
        font-size: 24rpx;
        color: #ffa31a;
        background-color: #ffead4;
        border-radius: 8rpx;
      }
    }
    .tipsMobile {
      word-wrap: break-word;
      white-space: normal;
      margin-bottom: 8rpx;
    }
  }
}
.fixed {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding: 14rpx 24rpx 60rpx 24rpx;
  background-color: #fff;
  & button {
    font-size: 26rpx;
    height: 76rpx;
    line-height: 76rpx;
    border-radius: 44rpx;
    color: #fff;
    background: $uni-color-motif;
  }
}
</style>
